<?php

namespace App\Repositories;

use App\Models\EntryTally;
use App\Models\Order;
use App\Models\SignOutTally;
use Illuminate\Support\Facades\DB;

class HomeRepository extends BaseRepository
{
    public function model()
    {
        return Order::class;
    }

    /**
     * 获取首页数据
     * Date: 2018/06/02
     * @author Tenny
     * @param $service_id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getHomes($service_id)
    {
        $result = [
            'entry_total' => 0,
            'zt_entry' => 0,
            'ps_entry' => 0,
            'sign_total' => 0,
            'zt_sign' => 0,
            'ps_sign' => 0,
            'income' => 0,
        ];
        //计算首页数据
        $query = EntryTally::query();
        $entry = $query
            ->select(['type', DB::raw('count(id) as total_num'), DB::raw('sum(unit_price) as total_sum')])
            ->groupBy('type')
            ->where('service_id', '=', $service_id)
            ->whereBetween('created_at', [
                date("Y-m-d 00:00:00", time()),
                date("Y-m-d 23:59:59", time())
            ])
            ->get()
            ->toArray();
        $query2 = SignOutTally::query();
        $sign = $query2
            ->select(['type', DB::raw('count(id) as total_num'), DB::raw('sum(unit_price) as total_sum')])
            ->groupBy('type')
            ->where('service_id', '=', $service_id)
            ->where('status', '=', 0)
            ->whereBetween('created_at', [
                date("Y-m-d 00:00:00", time()),
                date("Y-m-d 23:59:59", time())
            ])
            ->get()
            ->toArray();
        if (is_array($entry) && count($entry)) {
            foreach ($entry as $item) {
                if ($item['type'] == 1) {
                    $result['entry_total'] += $item['total_num'];
                    $result['zt_entry'] += $item['total_num'];
                } else {
                    $result['entry_total'] += $item['total_num'];
                    $result['ps_entry'] += $item['total_num'];
                }
            }
        }
        if (is_array($sign) && count($sign)) {
            foreach ($sign as $item) {
                $result['income'] = round($result['income'] + $item['total_sum'], 2);
                if ($item['type'] == 1) {
                    $result['sign_total'] += $item['total_num'];
                    $result['zt_sign'] += $item['total_num'];
                } else {
                    $result['sign_total'] += $item['total_num'];
                    $result['ps_sign'] += $item['total_num'];
                }
            }
        }
        return $result;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}